package com.andong.service.impl;

import com.andong.domain.entity.Student;
import com.andong.domain.pojo.Result;
import com.andong.utils.BaseContext;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andong.domain.entity.CoachScore;
import com.andong.service.CoachScoreService;
import com.andong.mapper.CoachScoreMapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;

import static com.andong.utils.SystemConstant.*;

/**
* @author 王海云
* @description 针对表【coach_score(教练评分表)】的数据库操作Service实现
* @createDate 2024-01-13 14:37:49
*/
@Service
public class CoachScoreServiceImpl extends ServiceImpl<CoachScoreMapper, CoachScore>
    implements CoachScoreService{
    @Resource
    private CoachScoreMapper coachScoreMapper;
    @Override
    public Result getAverage(Long id) {
        Double score = coachScoreMapper.getAverage(id);
        return Result.success(score);
    }

    @Override
    public Result saveOrModify(CoachScore coachScore) {
        if (coachScore.getScore() <= MIN_SCORE || coachScore.getScore() > MAX_SCORE) {
            return Result.error(SELECT_SCORE_ERROR);
        }
        // 检查身份
        Long studentId = (Long) BaseContext.getCurrentIdAndIdentity().get(CURRENT_ID);
        Student student = Db.getById(studentId, Student.class);
        if (!coachScore.getStudentId().equals(studentId)) {
            return Result.error(COACH_SCORE_ERROR);
        }
        if (!coachScore.getCoachId().equals(student.getCoachId())) {
            return Result.error(COACH_SCORE_SELF_ERROR);
        }
        saveOrUpdate(coachScore);
        return Result.success();
    }

    @Override
    public Result getScoreByStudentId(Long studentId, Long coachId) {
        CoachScore coachScore = lambdaQuery()
                .eq(CoachScore::getStudentId, studentId)
                .eq(CoachScore::getCoachId, coachId)
                .one();
        return Result.success(coachScore);
    }
}




